package producer.config;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.zookeeper.CreateMode;
import producer.entity.CenterConfigOuterClass;

/**
 * @ClassName CenterConfig
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2022/1/11 上午1:29
 * @Version V1.0
 * @Since JDK 11
 */
public class CenterConfig {

    public static int port = AppConfig.port;

    public void register() throws Exception {
        //注册节点
        //注册信息
        //ip
        byte[] bytes = null;
        String configPath = "/" + AppConfig.group + "_config/" + AppConfig.version + "/" + AppConfig.name;
        try {
            bytes = ZKConfig.client.getData().forPath(configPath);
        } catch (Exception e) {

        }
        if(bytes == null){
            CenterConfigOuterClass.CenterConfig centerConfig = CenterConfigOuterClass.CenterConfig.newBuilder().setPort(port).build();
            ZKConfig.client.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT)
                    .forPath(configPath,centerConfig.toByteArray());
        }else {
            port = CenterConfigOuterClass.CenterConfig.parseFrom(bytes).getPort();
        }
        NodeCache nodeCache = new NodeCache(ZKConfig.client, configPath);
        nodeCache.getListenable().addListener(()->{
            ChildData currentData = nodeCache.getCurrentData();
            if(currentData != null){
                byte[] data = currentData.getData();
                if(data != null){
//                    port = CenterConfigOuterClass.CenterConfig.parseFrom(data).getPort();
                }
            }
        });
    }
}
